package com.cpr.demo.service.mq.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cpr.demo.constant.MyMqConstant;
import com.cpr.demo.model.mq.SingleMqReport;
import com.cpr.demo.mycraft.mq.redis.RedisMessage;
import com.cpr.demo.repository.mq.SingleMqReportRepository;
import com.cpr.demo.service.mq.SingleMqReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Chen Panrui
 * created at 2021/10/18 17:20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SingleMqReportServiceImpl implements SingleMqReportService {

    private final SingleMqReportRepository singleMqReportRepository;

    @Override
    public void savePublish(String queueName, RedisMessage publishMessage, String publishNode) {
        log.info("发送消息队列={},发布消息={},发布节点={},messageId={}", queueName, publishMessage.getMessage(), publishNode, publishMessage.getMessageId());
        SingleMqReport model = new SingleMqReport();
        model.setMessageId(publishMessage.getMessageId());
        model.setStatus(MyMqConstant.MESSAGE_STATUS_SEND);
        model.setHandleType(MyMqConstant.MQ_TYPE_REDIS_SINGLE);
        model.setQueueName(queueName);
        model.setPublishMessage(publishMessage.getMessage());
        model.setPublishNode(publishNode);
        model.setPublishTime(DateTime.now());
        singleMqReportRepository.insert(model);
    }

    @Override
    public void saveReceive(String queueName, RedisMessage receiveMessage, String receiveNode) {
        log.info("接收消息队列={},接收消息={},接收节点={},messageId={}", queueName, receiveMessage.getMessage(), receiveNode, receiveMessage.getMessageId());
        QueryWrapper<SingleMqReport> query = new QueryWrapper<>();
        query.eq("message_id", receiveMessage.getMessageId());
        List<SingleMqReport> list = singleMqReportRepository.selectList(query);
        if(CollectionUtil.isEmpty(list)){
            log.info("*****无messageId={}的数据", receiveMessage.getMessageId());
            return;
        }
        if(list.size()>1){
            log.info("*****messageId={}重复", receiveMessage.getMessageId());
            return;
        }
        SingleMqReport model = list.get(0);
        model.setReceiveNode(receiveNode);
        model.setReceiveMessage(receiveMessage.getMessage());
        model.setReceiveTime(DateTime.now());
        model.setStatus(MyMqConstant.MESSAGE_STATUS_RECEIVE);
        singleMqReportRepository.updateById(model);
    }
}
